package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import pojo.*;
import service.TeaMenuService;
import service.TeacherService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;

import static sf.constant.DISPLAY_BLOCK;
import static sf.constant.DISPLAY_NONE;

/**
 * @author tao
 * @date 2021/11/10
 */

@Controller
@RequestMapping("/hms")
public class TeacherController {

    @Autowired
    @Qualifier("teacherServiceImpl")
    private TeacherService teacherService;
    @Autowired
    @Qualifier("teaMenuServiceImpl")
    private TeaMenuService teaMenuService;

    //跳转到老师登录界面
    @RequestMapping("/TeacherLogin")
    public String index3(){
        return "TeacherLogin";
    }

    @RequestMapping("/toAddClazz")
    public String index4(){
        return "teacher/createClazz";
    }

    //跳转到教师系统
    @RequestMapping("/teacherSystem1")
    public String index5(Model model,HttpSession session){
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        List<Clazz> clazzes = teaMenuService.selectAllClazz(teacher.getId());
        model.addAttribute("clazz",clazzes);
        List<Student> students = teaMenuService.selectAllStudent(teacher.getId());
        model.addAttribute("student",students);
        List<Work> works = teaMenuService.selectAllWork(teacher.getId());
        model.addAttribute("work",works);
        return "teacher/teacherSystem1";
    }

    @RequestMapping("/toUpdateClazz")
    public String index6(Model model,int id){
        Clazz clazz = teaMenuService.selectClazz(id);
        model.addAttribute("clazz",clazz);
        return "teacher/updateClazz";
    }

    @RequestMapping("/updateClazz")
    public String index7(Clazz clazz){
        int i = teaMenuService.updateClazz(clazz);
        System.out.println(i);
        return "redirect:/hms/teacherSystem1";
    }

    @RequestMapping("/toAddStudent")
    public String index8(Model model,HttpSession session){
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        List<Clazz> clazzes = teaMenuService.selectAllClazz(teacher.getId());
        model.addAttribute("clazz",clazzes);
        return "teacher/addStudent";
    }

    @RequestMapping("/teaLogin")
    public String teacherLogin(Model model, Teacher teacher, HttpSession session){
        //由下面4个语句打印的结果可以看出，进行了两次查询
        if (teacherService.selectTeacher(teacher.getId())!= null) {
            if (teacher.getPassword().equals(teacherService.teacherPassword(teacher.getId()).getPassword())) {
                model.addAttribute("display", DISPLAY_NONE);
                model.addAttribute("Register", "登录成功");
                if (session.getAttribute("teacher")!=null){
                    return "redirect:/hms/teacherSystem1";
                }
                Teacher teacher1 = teacherService.selectTeacher(teacher.getId());
                session.setAttribute("teacher",teacher1);
                return "redirect:/hms/teacherSystem1";
            } else {
                model.addAttribute("display", DISPLAY_BLOCK);
                model.addAttribute("Register", "用户名或密码错误");
                return "redirect:/hms/TeacherLogin";
            }
        }else {
            model.addAttribute("display", DISPLAY_BLOCK);
            model.addAttribute("Register", "教师用户名未注册");
            return "redirect:/hms/TeacherLogin";
        }
    }

    //退出登录
    @RequestMapping("/teaLogout")
    public String logout(HttpSession session){
        //session过期
        session.invalidate();
        return "index";
    }

    @RequestMapping("/addClazz")
    public String addCLazz(Clazz addClazz,HttpSession session){
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        addClazz.setTeacherID(teacher.getId());
        System.out.println(addClazz);
        teaMenuService.addClazz(addClazz);
        return "redirect:/hms/teacherSystem1";
    }

    @RequestMapping("/toDeleteClazz/{id}")
    public String deleteCLazz(@PathVariable("id")int id){
        System.out.println(id);
        teaMenuService.deleteClazz1(id);
        teaMenuService.deleteClazz(id);
        System.out.println("删除班级");

        return "redirect:/hms/teacherSystem1";
    }

    @RequestMapping("/addStudent")
    public String selectStudent(Model model,ClazzAndStudent cs){
        if (cs.getName().equals(teaMenuService.selectOneStudent(cs.getStudentID()).getName())){
            if (teaMenuService.addStudent(cs)>0){
                return "redirect:/hms/teacherSystem1";
            }
        }
        model.addAttribute("error","学生姓名或学号错误！");
        return "redirect:/hms/toAddStudent";
    }

    @RequestMapping("/toAddWork")
    public String index9(Model model,HttpSession session){
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        List<Clazz> clazzes = teaMenuService.selectAllClazz(teacher.getId());
        model.addAttribute("clazz",clazzes);
        return "teacher/addWork";
    }

    @RequestMapping("/addWork")
    public String addWork(@RequestParam("files") CommonsMultipartFile files, Work work,  HttpServletRequest request,HttpSession session){
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        System.out.println("---------------------");
        String uploadFileName = files.getOriginalFilename();
        //如果文件名为空，直接回到首页！
        System.out.println("上传文件名 : "+uploadFileName);
        //==========多加一步创建，文件夹总是创建不成功===========
        String path1 = "D:/upload";
        File realPath1 = new File(path1);
        if (!realPath1.exists()){
            realPath1.mkdir();
        }
        //=================================================
        //上传路径保存设置
        String path = "D:/upload/"+teacher.getId()+"+"+teacher.getName();
        //如果路径不存在，创建一个
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
            files.transferTo(new File(realPath +"/"+ uploadFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将文件路径写入数据库
        if (!"".equals(uploadFileName)){
            work.setFileName(realPath+"\\"+uploadFileName);
        }
        work.setTeacher_id(teacher.getId());
        teaMenuService.addWork(work);
        int wid = work.getWid();
        int[] ints = teaMenuService.selectClazzStudent(work.getClazz_id());
        for (int anInt : ints) {
            teaMenuService.addStuWork(anInt, wid);
        }

        return "redirect:/hms/teacherSystem1";
    }

    @RequestMapping("/toCorrectWork/{wid}/{title}/{cname}")
    public String index10(@PathVariable("wid")int wid,@PathVariable("title")String title,@PathVariable("cname")String cname,Model model){
        List<MyWork> myWorks = teaMenuService.selectStudentWork(wid);
        model.addAttribute("studentWorks",myWorks);
        model.addAttribute("wid",wid);
        model.addAttribute("title",title);
        model.addAttribute("cname",cname);
        for (MyWork myWork:myWorks){
            System.out.println(myWork);
        }
        return "teacher/homeWorkCorrecting";
    }


    @RequestMapping("/toAWork/{swid}/{title}/{cname}/{wid}")
    public String index11(@PathVariable("swid")int swid,@PathVariable("title")String title,@PathVariable("cname")String cname,@PathVariable("wid")int wid,Model model){
        MyWork myWork = teaMenuService.selectAStudentWork(swid);
        model.addAttribute("swid",swid);
        model.addAttribute("AWork",myWork);
        model.addAttribute("wid",wid);
        model.addAttribute("title",title);
        model.addAttribute("cname",cname);
        return "teacher/correctAStudentWork";
    }

    @RequestMapping("/{sid}/download")
    public String downloads(@PathVariable("sid")int sid, HttpServletResponse response , HttpServletRequest request) throws Exception{
        //要下载的文件地址
        MyWork myWork = teaMenuService.selectAStudentWork(sid);
        String fileName1 = myWork.getFileName();

        File fileP = new File(fileName1);
        String  fileName = fileP.getName();

        //1、设置response 响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition",
                "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

        //2、 读取文件--输入流
        InputStream input=new FileInputStream(fileP);
        //3、 写出文件--输出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index;
        //4、执行 写出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return "";
    }

    @ResponseBody
    @RequestMapping("/{swid}/workWin")
    public String workWin(@PathVariable("swid")int swid,float score) {
        System.out.println(swid);
        System.out.println(score);
        teaMenuService.updateAStudentWork(swid, score);
        return "";
    }


    @RequestMapping("/toUpdateWork")
    public String index9(int id,Model model,HttpSession session){
        Work work = teaMenuService.selectWork(id);
        System.out.println(work);
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        List<Clazz> clazzes = teaMenuService.selectAllClazz(teacher.getId());
        model.addAttribute("clazz",clazzes);
        model.addAttribute("work",work);
        return "teacher/updateWork";
    }

    @RequestMapping("/updateWork")
    public String updateWork(Work work){
        System.out.println(work);
        teaMenuService.updateWork(work);
        return "redirect:/hms/teacherSystem1";
    }

    @RequestMapping("/toDeleteWork/{tid}")
    public String deleteWork(@PathVariable("tid")int id){
        teaMenuService.deleteStudentWork(id);
        teaMenuService.deleteWork(id);
        return "redirect:/hms/teacherSystem1";
    }


    

}
